package com.study.controller.system;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.study.common.JsonDTo;
import com.study.model.Database;
import com.study.model.GoodsClass;
import com.study.service.ToolService;
import com.study.util.DateUtil;
import com.study.util.InitConfig;
import com.study.util.Page;

@Controller
public class ToolController {

    private final static Logger logger = Logger.getLogger(ToolController.class);

    @Autowired
    private ToolService toolService;

    @RequestMapping(value = "/database/dataBaseList")
    public String dataBaseList(HttpServletRequest request, HttpServletResponse response) {
        return "database/dataList.jsp";
    }

    @RequestMapping(value = "/database/getLists")
    public @ResponseBody
    Page getLists(HttpServletRequest request, HttpServletResponse response) {
        Page objects = new Page();
        String pageNo = request.getParameter("pageNo");
        objects.setPageNo(Integer.parseInt(pageNo));
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("page", (objects.getPageNo() - 1) * objects.getPageSize());
            paramMap.put("pageSize", objects.getPageSize());
            List<Database> roleEntitys = toolService.getDatabaseLists(paramMap);
            int total = toolService.getTotalDatabaseLists(paramMap);

            objects.setTotalPages(objects.getPages(total));
            objects.getResult().addAll(roleEntitys);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return objects;
    }

    @RequestMapping(value = "/database/save")
    public @ResponseBody
    JsonDTo saveDatabase(HttpServletRequest request, HttpServletResponse response) {
        InputStream in = null;
        InputStreamReader inReader = null;
        BufferedReader br = null;
        OutputStreamWriter writer = null;
        FileOutputStream fout = null;
        try {
            String backup = InitConfig.getProperty("backup");
            Process process = Runtime.getRuntime().exec(backup);

            in = process.getInputStream();
            inReader = new InputStreamReader(in, "utf8");

            String inStr;
            StringBuffer sb = new StringBuffer("");
            String outStr;
            br = new BufferedReader(inReader);
            while ((inStr = br.readLine()) != null) {
                sb.append(inStr + "\r\n");
            }
            outStr = sb.toString();

            Long now = System.currentTimeMillis();
            String name = DateUtil.longToString(now, "yyyyMMddHHmmss");
            String path = InitConfig.getProperty("backupPath") + name + ".sql";

            File file = new File(path);
            if (!file.exists()) {
                file.createNewFile();
            }

            Database obj = new Database();
            obj.setCreateor(request.getSession().getAttribute("account").toString());
            obj.setName(DateUtil.longToString(now, "yyyy-MM-dd"));

            // 要用来做导入用的sql目标文件：
            fout = new FileOutputStream(path);
            writer = new OutputStreamWriter(fout, "utf8");
            writer.write(outStr);
            writer.flush();
            obj.setPath(path);
            toolService.save(obj);
            return JsonDTo.getSuccess();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return JsonDTo.getFail();
        } finally {
            try {
                in.close();
                inReader.close();
                br.close();
                writer.close();
                fout.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping(value = "/database/del")
    public @ResponseBody
    JsonDTo del(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("id", request.getParameter("id"));
            paramMap.put("path", request.getParameter("path"));
            toolService.del(paramMap);
            return JsonDTo.getSuccess();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return JsonDTo.getFail();
        }
    }

    @PostConstruct
    public void initDatabase() {
        InputStream in = null;
        InputStreamReader inReader = null;
        BufferedReader br = null;
        OutputStreamWriter writer = null;
        FileOutputStream fout = null;
        try {
            Long now = System.currentTimeMillis();
            String searchValue = "%" + DateUtil.longToString(now, "yyyy-MM") + "%";
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("searchValue", searchValue);
            List<Database> list = toolService.getDatabaseByMonth(paramMap);
            if (list.size() == 0) {
                String backup = InitConfig.getProperty("backup");
                Process process = Runtime.getRuntime().exec(backup);

                in = process.getInputStream();
                inReader = new InputStreamReader(in, "utf8");

                String inStr;
                StringBuffer sb = new StringBuffer("");
                String outStr;
                // 组合控制台输出信息字符串
                br = new BufferedReader(inReader);
                while ((inStr = br.readLine()) != null) {
                    sb.append(inStr + "\r\n");
                }
                outStr = sb.toString();
                String name = DateUtil.longToString(now, "yyyyMMddHHmmss");
                String path = InitConfig.getProperty("backupPath") + name + ".sql";
                File file = new File(path);
                if (!file.exists()) {
                    file.createNewFile();
                }
                Database obj = new Database();
                obj.setCreateor("admin");
                obj.setName(DateUtil.longToString(now, "yyyy-MM-dd"));

                // 要用来做导入用的sql目标文件：
                fout = new FileOutputStream(path);
                writer = new OutputStreamWriter(fout, "utf8");
                writer.write(outStr);
                writer.flush();
                obj.setPath(path);
                toolService.save(obj);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (inReader != null) {
                    inReader.close();
                }
                if (br != null) {
                    br.close();
                }
                if (writer != null) {
                    writer.close();
                }
                if (fout != null) {
                    fout.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping(value = "/database/download")
    public void download(HttpServletRequest request, HttpServletResponse response, String path) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition",
                    "attachment; filename=" + path.substring(path.lastIndexOf("/") + 1, path.length()));// 设定输出文件头
            response.setContentType("application/msexcel");// 定义输出类型
            DataInputStream in = new DataInputStream(new FileInputStream(new File(path)));
            OutputStream out = response.getOutputStream();
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            out.close();
            in.close();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    @RequestMapping(value = "/goodsClass/getAllGoodsClass")
    public @ResponseBody JsonDTo getAllGoodsClass(HttpServletRequest request, HttpServletResponse response, String path) {
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            List<GoodsClass> objs = toolService.getAllGoodsClass(paramMap);
            return JsonDTo.getSuccess(objs);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return JsonDTo.getFail();
        }
    }
    
    @RequestMapping(value = "/tool/getWpmcByTid")
    public @ResponseBody JsonDTo getWpmcByTid(HttpServletRequest request, HttpServletResponse response) {
    	try {
    		Map<String, Object> paramMap = new HashMap<String, Object>();
    		paramMap.put("tid",request.getParameter("tid"));
    		Map<String, Object> obj = toolService.getWpmcByTid(paramMap);
    		return JsonDTo.getSuccess(obj);
    	} catch (Exception e) {
    		logger.error(e.getMessage(), e);
    		return JsonDTo.getFail();
    	}
    }
}